/****************************************************************************
@FILENAME:	codec_v8t04a.c
@FUNCTION:	decode v8t04a
@AUTHOR:	flege.zhang
@DATE:		2020.03.31
*****************************************************************************/


#include "codec_v8t04a.h"
#include "key_process.h"


#if((HW_DETECT_TYPE == DECODE_V8T04A_TYPE) || (HW_DETECT_TYPE == DECODE_V8T04A_16_TYPE))
uint8_t decoded_curr_state = DEC_V8T04A_STATE_HEADER;
uint8_t decoded_curr_bit = DECODE_DATA_BIT_NUM;

extern str_key_info key_info;


/****************************V8T04A ENCODE FORMAT****************************/
/****************************************************************************
                    ____                 ____2ms____
           HEAD:        \_____3.5ms_____/           \
           
                    ____            ___0.74ms___
           BIT1:        \__0.37ms__/            \
           
                    ____            __0.37ms__
           BIT0:        \__0.37ms__/          \
*****************************************************************************/

void decode_v8t04a_init()
{
	decoded_curr_bit = DECODE_DATA_BIT_NUM;
	decoded_curr_state = DEC_V8T04A_STATE_HEADER;

	memset(&key_info,0x0,sizeof(str_key_info));
}

void decode_v8t04a(uint16_t time_low,uint16_t time_high)
{
	switch(decoded_curr_state)
	{
		case DEC_V8T04A_STATE_HEADER:
		{
			key_info.curr_key = 0x0;
			decoded_curr_bit = DECODE_DATA_BIT_NUM;

			if(IS_V8T04A_HEADER(time_low,time_high))
			{
				decoded_curr_state = DEC_V8T04A_STATE_DATA;
			}
			else
			{
				decoded_curr_state = DEC_V8T04A_STATE_HEADER;
			}
			break;
		}
		case DEC_V8T04A_STATE_DATA:
		{
			--decoded_curr_bit;
			
			if(IS_V8T04A_BIT1(time_low,time_high))
			{
				key_info.curr_key |= 1<<decoded_curr_bit;				
			}

			//check decode end?
			if(0 == decoded_curr_bit)
			{
				if((key_info.curr_key&DECODE_DATA_CHECK_VALUE) == DECODE_DATA_CHECK_VALUE)
				{
					key_info.handle_flag = 0x01;
					
					if(key_info.last_key == key_info.curr_key)
					{
						++key_info.pressed_time;
					}
					else
					{
						key_info.pressed_time = 0x0;
					}

					key_info.last_key = key_info.curr_key;
				}
				
				decoded_curr_state = DEC_V8T04A_STATE_HEADER;
#if LOG_SECONDARY
				print("D:%x,C:%d\n",key_info.curr_key,key_info.pressed_time);
#endif
#ifdef SINGLE_LED_GPIO_INDEX
				led_set(key_info.curr_key,0x01);
#elif((defined MORE_LED_GPIOS) && (defined LED_ON_WHEN_TOUCHED))
#if(LOCK_KEY_ENABLE)
				//lock is on,don't allow to on/off other key
				if(!get_key_lock_flag())
#endif
				{
					led_set(key_info.curr_key,0x01);
				}
#endif
			}
			
			break;
		}
	}
}

void decode_v8t04a_end(void)
{	
#ifdef SINGLE_LED_GPIO_INDEX
	led_set(0x00,0x00);
#elif((defined MORE_LED_GPIOS) && (defined LED_ON_WHEN_TOUCHED))
	led_set_all(0x0);
#endif
	//reset decoded data
	decode_v8t04a_init();

#if LOG_SECONDARY
	print("T\n");
#endif
}
#endif

